/**
 * Created by jiangqifan on 16/3/2.
 */
/**
 * Created by jiangqifan on 16/3/2.
 */

var mongoose = require('mongoose');
var logger = require('log4js').getLogger();
require('mongoose').Promise = global.Promise
module.exports.open = function(config) {

    // // Connect to the tasklocker MongoDB
    // mongoose.connect(config.url, config.config, function(err) {
    //     if(err) {
    //         console.log('connection error', err);
    //     } else {
    //         console.log('connection successful');
    //     }
    // });

    // mongoose.connect();
    var db = mongoose.connection;
    var host = config.host;
    var port = config.port;
    var database = config.database;
    var options = config.options;
    options.server.reconnectTries = Number.MAX_VALUE;
    db.open(host, database, port, options);
    db.on('error', function (err) {
        logger.info("connect error :" + err);
        db.close();
    });
    //监听db close event并重新连接
    db.once('open',function(){
        logger.info('mongodb  opened')
    })
    db.on('close', function () {
        logger.info("connect close retry connect ");
    });
    db.on('connection',function(){
        logger.info('mongodb connection');
    });

    db.on('connected',function(){
        logger.info('mongodb connected');
    });


    db.on('disconnecting',function(){
        logger.info('mongodb disconnecting');
    });

    db.on('disconnected',function(){
        logger.info('mongodb disconnected');
    });

    db.on('reconnected',function(err,data){
        logger.info('mongodb reconnected');
    });
    return db;
}
